import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.*;
import java.util.*;

// tcp 的客户端---传输的字节流
public class TcpEchoclient {
    Socket socket = null;
    private String ip;
    private int port;

    TcpEchoclient(String ip, int port) throws IOException {
        socket = new Socket(ip, port);
    }

    public void start() {
        System.out.println(" 客户端启动 ");
        Scanner scanner=new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner in = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                System.out.print("->");

                // 将请求写进去
                String request = scanner.next();
                writer.println(request);
                writer.flush();

                String respond = in.next();
                System.out.println(respond);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   /*public void start() {
       // tcp 的客户端行为和 udp 的客户端差不多.
       // 都是:
       // 3. 从服务器读取响应.
       // 4. 把响应显示到界面上.
       Scanner scanner = new Scanner(System.in);
       try (InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
           PrintWriter writer = new PrintWriter(outputStream);
           Scanner scannerNetwork = new Scanner(inputStream);
           while (true) {
               // 1. 从控制台读取用户输入的内容
               System.out.print("-> ");
               String request = scanner.next();
               // 2. 把字符串作为请求, 发送给服务器
               //    这里使用 println, 是为了让请求后面带上换行.
               //    也就是和服务器读取请求, scanner.next 呼应
               writer.println(request);
               writer.flush();
               // 3. 读取服务器返回的响应.
               String response = scannerNetwork.next();
               // 4. 在界面上显示内容了.
               System.out.println(response);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }*/

    public static void main(String[] args) throws IOException {
        TcpEchoclient echoclient = new TcpEchoclient("127.0.0.1", 9090);
        echoclient.start();
    }
}